package com.eage.security.login.impl;


import com.eage.security.domain.ShiroUserDetail;
import com.eage.security.properties.CompanyProperties;
import com.eage.security.login.inter.UserLogin;
import com.eage.security.mobilevalidate.MobileRedisProvider;
import com.eage.security.login.ShiroUserDetailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: lex
 * @Date: 2019/2/1
 */
@Slf4j
@Component
public  class MobileUserLoginImpl implements UserLogin {

    @Autowired
    private CompanyProperties companyProperties;

    @Autowired
    private MobileRedisProvider mobileRedisProvider;

    @Resource
    private ShiroUserDetailService shiroUserDetailServiceImpl;

    @Override
    public AuthenticationInfo doGetAuthenticationInfo(UsernamePasswordToken token) throws AuthenticationException {
        log.warn("现在为手机验证码登入");
        ShiroUserDetail shiroUserDetail = this.getUserDetail(token);
        return new SimpleAuthenticationInfo(shiroUserDetail,  token.getPassword(), shiroUserDetail.getUserId());
    }

    @Override
    public ShiroUserDetail getUserDetail(UsernamePasswordToken token) throws AuthenticationException {
        //前端传入的手机号
        String mobile = token.getUsername().split(":"+ companyProperties.getLoginSplit()+":")[1];
        //前端传回来的code
        String code = new String(token.getPassword());
        mobileRedisProvider.validate(mobile, code);
        return shiroUserDetailServiceImpl.getByMobile(mobile);
    }
}
